package com.demo.explore.sender;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

/**
 * 验证码发送器
 *
 * @author Logan
 *
 */
@Component
public class ValidateCodeSender {

    /**
     * 模拟发送手机验证码，此处发回浏览器，实际情况根据短信服务商做调整
     *
     * @param response HTTP响应对象
     * @param mobile 手机号
     * @param code 验证码
     */
    public void sendSmsCode(HttpServletResponse response, String mobile, String code) {
        System.out.println(String.format("模拟向手机号【%s】发送验证码【%s】", mobile, code));
        write(response, "验证码为：" + code);
    }

    /**
     * 发送HTTP响应信息
     *
     * @param response HTTP响应对象
     * @param message 信息内容
     */
    private void write(HttpServletResponse response, String message) {
        response.setContentType("text/html; charset=UTF-8");

        try (
                PrintWriter writer = response.getWriter();
        ) {
            writer.write(message);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}